package com.dullong.firedocmanager.Controller.page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dullong.firedocmanager.bean.User;
import com.dullong.firedocmanager.service.UserService;

@Controller
public class LogonPage {

	@Autowired
	UserService userService;

	@RequestMapping("/logon.html")
	public String logon(HttpServletRequest request, HttpServletResponse response) {
		return "logon";
	}

	@RequestMapping(value = "logon_logon.html", method = RequestMethod.POST)
	public ModelAndView logon_logon(HttpServletRequest request,
			HttpServletResponse response, HttpSession session,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "psw", required = true) String psw) {
		ModelAndView view = new ModelAndView();
		User userByUP = userService.getUserByUP(username, psw);
		if (userByUP == null) {
			view.addObject("message", "账号或密码错误！");
			view.addObject("logon", "logon");
			view.setViewName("logon");
		} else {
			session.setAttribute("user", userByUP);
			view.setViewName("redirect:admin");
		}
		return view;
	}

	@RequestMapping(value = "logon_reg.html", method = RequestMethod.POST)
	public ModelAndView logon_reg(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "psw", required = true) String psw) {
		ModelAndView view = new ModelAndView();
		boolean exist = userService.isExist(username, email);
		if (exist) {
			view.addObject("message", "账号或邮箱已经存在，请换个重新注册！");
			view.addObject("logon", "reg");
			view.setViewName("logon");
		} else {
			User user = new User();
			user.setUserName(username);
			user.setPSW(psw);
			user.setEmail(email);
			userService.save(user, -1);
			view.addObject("message", "注册成功，请进入登陆！");
			view.setViewName("redirect:logon.html");
		}
		return view;
	}

}
